<template>
  <div class="withdrawal-container">
    <!-- 提现概览 -->
    <el-row :gutter="20" class="overview-section">
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="overview-content">
            <div class="overview-icon available">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">¥{{ formatMoney(balanceInfo.availableBalance) }}</div>
              <div class="overview-label">可提现余额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="overview-content">
            <div class="overview-icon frozen">
              <el-icon><Lock /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">¥{{ formatMoney(balanceInfo.frozenBalance) }}</div>
              <div class="overview-label">冻结金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="overview-content">
            <div class="overview-icon pending">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">¥{{ formatMoney(balanceInfo.pendingBalance) }}</div>
              <div class="overview-label">在途金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="overview-content">
            <div class="overview-icon total">
              <el-icon><Money /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">¥{{ formatMoney(balanceInfo.totalWithdrawn) }}</div>
              <div class="overview-label">累计提现</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 提现申请 -->
    <el-card shadow="hover" class="withdrawal-form-card">
      <template #header>
        <div class="card-header">
          <span>申请提现</span>
          <el-tag v-if="riskWarning" type="warning">{{ riskWarning }}</el-tag>
        </div>
      </template>
      
      <el-form :model="withdrawalForm" :rules="withdrawalRules" ref="withdrawalFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提现金额" prop="amount">
              <el-input
                v-model="withdrawalForm.amount"
                placeholder="请输入提现金额"
                type="number"
                :min="100"
                :max="balanceInfo.availableBalance"
              >
                <template #suffix>元</template>
              </el-input>
              <div class="form-tip">
                最低提现金额：¥100，可提现余额：¥{{ formatMoney(balanceInfo.availableBalance) }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提现方式" prop="method">
              <el-select v-model="withdrawalForm.method" placeholder="请选择提现方式" style="width: 100%">
                <el-option label="银行卡" value="bank" />
                <el-option label="支付宝" value="alipay" />
                <el-option label="微信" value="wechat" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="收款账户" prop="account">
          <el-input
            v-model="withdrawalForm.account"
            :placeholder="getAccountPlaceholder()"
          />
        </el-form-item>
        
        <el-form-item label="账户姓名" prop="accountName">
          <el-input
            v-model="withdrawalForm.accountName"
            placeholder="请输入账户持有人姓名"
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="withdrawalForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitWithdrawal" :loading="submitting">
            申请提现
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 提现记录 -->
    <el-card shadow="hover" class="withdrawal-records-card">
      <template #header>
        <div class="card-header">
          <span>提现记录</span>
          <div class="header-actions">
            <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 120px; margin-right: 10px">
              <el-option label="全部" value="" />
              <el-option label="处理中" value="pending" />
              <el-option label="已完成" value="completed" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
            <el-button @click="refreshRecords">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="withdrawalRecords" v-loading="loading" stripe>
        <el-table-column prop="id" label="申请编号" width="120" />
        <el-table-column prop="amount" label="提现金额" width="120">
          <template #default="{ row }">
            ¥{{ formatMoney(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="method" label="提现方式" width="100">
          <template #default="{ row }">
            <el-tag :type="getMethodType(row.method)">{{ getMethodText(row.method) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="account" label="收款账户" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" />
        <el-table-column prop="processTime" label="处理时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              link
              @click="cancelWithdrawal(row)"
            >
              取消
            </el-button>
            <el-button type="primary" link @click="viewDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div v-if="totalRecords > 0" class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRecords"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getWithdrawalRecords"
          @current-change="getWithdrawalRecords"
        />
      </div>
    </el-card>

    <!-- 提现详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="提现详情"
      width="600px"
    >
      <el-descriptions v-if="detailDialog.data" :column="2" border>
        <el-descriptions-item label="申请编号">{{ detailDialog.data.id }}</el-descriptions-item>
        <el-descriptions-item label="提现金额">¥{{ formatMoney(detailDialog.data.amount) }}</el-descriptions-item>
        <el-descriptions-item label="提现方式">{{ getMethodText(detailDialog.data.method) }}</el-descriptions-item>
        <el-descriptions-item label="收款账户">{{ detailDialog.data.account }}</el-descriptions-item>
        <el-descriptions-item label="账户姓名">{{ detailDialog.data.accountName }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ detailDialog.data.processTime || '未处理' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detailDialog.data.status)">{{ getStatusText(detailDialog.data.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailDialog.data.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item v-if="detailDialog.data.rejectReason" label="拒绝原因" :span="2">
          {{ detailDialog.data.rejectReason }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Wallet,
  Lock,
  Timer,
  Money,
  Refresh
} from '@element-plus/icons-vue'

// 余额信息
const balanceInfo = reactive({
  availableBalance: 0,
  frozenBalance: 0,
  pendingBalance: 0,
  totalWithdrawn: 0
})

// 提现表单
const withdrawalForm = reactive({
  amount: '',
  method: '',
  account: '',
  accountName: '',
  remark: ''
})

const withdrawalFormRef = ref(null)
const submitting = ref(false)

// 表单验证规则
const withdrawalRules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value < 100) {
          callback(new Error('最低提现金额为100元'))
        } else if (value > balanceInfo.availableBalance) {
          callback(new Error('提现金额不能超过可用余额'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  method: [
    { required: true, message: '请选择提现方式', trigger: 'change' }
  ],
  account: [
    { required: true, message: '请输入收款账户', trigger: 'blur' }
  ],
  accountName: [
    { required: true, message: '请输入账户姓名', trigger: 'blur' }
  ]
}

// 提现记录
const withdrawalRecords = ref([])
const loading = ref(false)
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(0)

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 风险警告
const riskWarning = computed(() => {
  // 这里可以根据商家的风险等级返回相应的警告信息
  return ''
})

// 格式化金额
const formatMoney = (amount) => {
  return (amount || 0).toLocaleString()
}

// 获取账户输入提示
const getAccountPlaceholder = () => {
  const placeholders = {
    bank: '请输入银行卡号',
    alipay: '请输入支付宝账号',
    wechat: '请输入微信号'
  }
  return placeholders[withdrawalForm.method] || '请先选择提现方式'
}

// 获取提现方式类型
const getMethodType = (method) => {
  const types = {
    bank: 'primary',
    alipay: 'success',
    wechat: 'warning'
  }
  return types[method] || 'info'
}

// 获取提现方式文本
const getMethodText = (method) => {
  const texts = {
    bank: '银行卡',
    alipay: '支付宝',
    wechat: '微信'
  }
  return texts[method] || method
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    completed: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '处理中',
    completed: '已完成',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

// 提交提现申请
const submitWithdrawal = async () => {
  try {
    await withdrawalFormRef.value.validate()
    
    await ElMessageBox.confirm(
      `确认申请提现 ¥${withdrawalForm.amount} 元？`,
      '确认提现',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    submitting.value = true
    
    // 这里调用提现API
    // const response = await submitWithdrawalRequest(withdrawalForm)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('提现申请已提交，请等待审核')
    resetForm()
    getWithdrawalRecords()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提现申请失败:', error)
      ElMessage.error(error.message || '提现申请失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  withdrawalFormRef.value?.resetFields()
  Object.assign(withdrawalForm, {
    amount: '',
    method: '',
    account: '',
    accountName: '',
    remark: ''
  })
}

// 获取提现记录
const getWithdrawalRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      status: filterStatus.value || undefined
    }
    
    // 这里调用获取提现记录API
    // const response = await getWithdrawalRecordsList(params)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    withdrawalRecords.value = []
    totalRecords.value = 0
    
  } catch (error) {
    console.error('获取提现记录失败:', error)
    ElMessage.error('获取提现记录失败')
  } finally {
    loading.value = false
  }
}

// 刷新记录
const refreshRecords = () => {
  getWithdrawalRecords()
}

// 取消提现
const cancelWithdrawal = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确认取消提现申请 ${record.id}？`,
      '取消提现',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里调用取消提现API
    // await cancelWithdrawalRequest(record.id)
    
    ElMessage.success('提现申请已取消')
    getWithdrawalRecords()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消提现失败:', error)
      ElMessage.error('取消提现失败')
    }
  }
}

// 查看详情
const viewDetail = (record) => {
  detailDialog.data = record
  detailDialog.visible = true
}

// 获取余额信息
const getBalanceInfo = async () => {
  try {
    // 这里调用获取余额信息API
    // const response = await getBalanceInfo()
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    Object.assign(balanceInfo, {
      availableBalance: 0,
      frozenBalance: 0,
      pendingBalance: 0,
      totalWithdrawn: 0
    })
    
  } catch (error) {
    console.error('获取余额信息失败:', error)
    ElMessage.error('获取余额信息失败')
  }
}

onMounted(() => {
  getBalanceInfo()
  getWithdrawalRecords()
})
</script>

<style scoped>
.withdrawal-container {
  padding: 20px;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.overview-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.overview-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.overview-icon.available {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.overview-icon.frozen {
  background: linear-gradient(135deg, #E6A23C, #F0A020);
}

.overview-icon.pending {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.overview-icon.total {
  background: linear-gradient(135deg, #F56C6C, #F78989);
}

.overview-info {
  flex: 1;
}

.overview-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.overview-label {
  font-size: 14px;
  color: #909399;
}

.withdrawal-form-card,
.withdrawal-records-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table) {
  margin-bottom: 0;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}
</style>
